package com.example.test.config;

import com.example.test.util.ResultBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.annotation.Resource;

@ControllerAdvice
public class BaseResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        System.out.println("响应拦截成功");
        System.out.println(body.getClass().toString());
        if(body instanceof String){ //返回值是String类型时，Spring会使用直接返回，如果再return ResultBean.success(body)返回会出现类型转换错误,如果返回值要通过ResultBean统一处理需要通过objectMapper类转换ResultBean类为json返回
            try {
                String json = objectMapper.writeValueAsString(ResultBean.success(body));//转成json
                //System.out.println(s);
                //return body;
                return json;
            } catch (JsonProcessingException e) {
                throw new RuntimeException("json转换失败");
            }
        }else if (body instanceof ResultBean) { //如果是ResultBean类实例直接返回
            return body;
        }else {
            return ResultBean.success(body);
        }
    }
}